<template>
  <div class="view-account">
    <div class="view-account-header"></div>
    <div class="view-account-container">
      <div class="view-account-top">
        <div class="view-account-top-logo">
          <img :src="websiteConfig.loginImage.value" alt="" />
        </div>
        <div class="view-account-top-desc">{{ websiteConfig.loginDesc }}</div>
      </div>
      <div class="view-account-form">
        <n-form
          ref="formRef"
          label-placement="left"
          size="large"
          :model="formInline"
          :rules="rules"
          v-if="loginType === 1"
        >
          <n-form-item path="username">
            <n-input v-model:value="formInline.username" placeholder="请输入手机号">
              <template #prefix>
                <n-icon size="18" color="#808695">
                  <PersonOutline />
                </n-icon>
              </template>
            </n-input>
          </n-form-item>
          <n-form-item path="password">
            <n-input
              v-model:value="formInline.password"
              type="password"
              showPasswordOn="click"
              placeholder="请输入密码"
            >
              <template #prefix>
                <n-icon size="18" color="#808695">
                  <LockClosedOutline />
                </n-icon>
              </template>
            </n-input>
          </n-form-item>
          <n-form-item class="default-color relative">
            <div class="flex justify-between">
              <div class="flex-initial">
                <n-checkbox v-model:checked="saveInfo">保存账号密码</n-checkbox>
              </div>
              <div class="flex-initial absolute right-0" @click="(loginType = 2)">
                <div class="cursor-pointer">忘记密码</div>
              </div>
            </div>
          </n-form-item>
        </n-form>
        <n-form
          ref="formRef"
          label-placement="left"
          size="large"
          :model="formInline"
          :rules="codeRules"
          v-if="loginType === 2"
        >
          <n-form-item path="username">
            <n-input v-model:value="formInline.username" placeholder="请输入手机号">
              <template #prefix>
                <n-icon size="18" color="#808695">
                  <PersonOutline />
                </n-icon>
              </template>
            </n-input>
          </n-form-item>
          <n-form-item path="password">
            <n-input-group>
              <n-input
                v-model:value="formInline.validCode"
                placeholder="请输入验证码"
              >
                <template #prefix>
                  <n-icon size="18" color="#808695">
                    <CheckCircleOutlined />
                  </n-icon>
                </template>
              </n-input>
              <n-button type="primary" ghost @click="sendcode">
                {{ sendCodeMsg }}
              </n-button>
            </n-input-group>
          </n-form-item>
          <n-form-item class="default-color relative">
            <div class="flex justify-between">
              <div class="flex-initial flex" @click="(loginType = 1)">
                <n-icon size="20" color="#808695">
                  <UserSwitchOutlined />
                </n-icon>
                <div class="cursor-pointer ml-1">账号密码登录</div>
              </div>
            </div>
          </n-form-item>
        </n-form>
        <n-button type="primary" @click="handleSubmit" size="large" :loading="loading" block>
          登录
        </n-button>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
  import { reactive, ref } from 'vue';
  import { useRoute, useRouter } from 'vue-router';
  import { md5 } from 'js-md5';
  import { useUserStore } from '@/store/modules/user';
  import { useMessage } from 'naive-ui';
  import { ResultEnum } from '@/enums/httpEnum';
  import { PersonOutline, LockClosedOutline } from '@vicons/ionicons5';
  import { UserSwitchOutlined, CheckCircleOutlined } from '@vicons/antd';
  import { PageEnum } from '@/enums/pageEnum';
  import { websiteConfig } from '@/config/website.config';
  import {loginPasswd, loginSms, sendCode} from "@/api/system/user";
  interface FormState {
    telephone: string;
    password: string;
    code: string,
  }

  const formRef = ref();
  const message = useMessage();
  const loading = ref(false);
  const saveInfo = ref(true);
  const LOGIN_NAME = PageEnum.BASE_LOGIN_NAME;

  const formInline = reactive({
    username: '',
    password: '',
    validCode: '',
    isCaptcha: true,
  });

  const rules = {
    username: { required: true, message: '请输入手机号', trigger: 'blur' },
    password: { required: true, message: '请输入密码', trigger: 'blur' },
  };

  const codeRules = {
    username: { required: true, message: '请输入手机号', trigger: 'blur' },
    validCode: { required: true, message: '请输入验证码', trigger: 'blur' },
  };

  const loginType = ref(1);
  const timeLimit = ref(-1);
  const sendCodeMsg = ref('发送');
  const timer = ref();

  const userStore = useUserStore();

  const router = useRouter();
  const route = useRoute();

  const handleSubmit = (e) => {
    e.preventDefault();
    formRef.value.validate(async (errors) => {
      if (!errors) {
        const { username, password, validCode } = formInline;
        if (loginType.value === 1) {
          localStorage.setItem('saveInfo', saveInfo.value ? '1' : '0');
          if (saveInfo.value) {
            localStorage.setItem("loginInfo", JSON.stringify({
              username,
              password,
            }));
          } else {
            localStorage.removeItem('loginInfo')
          }

        }
        message.loading('登录中...');
        loading.value = true;

        const params: FormState = {
          telephone: username,
          code: validCode,
          password: md5(password),
        };
        try {
          const { code, message: msg } = await userStore.login(params, loginType.value === 1 ? loginPasswd: loginSms);
          message.destroyAll();
          if (code == ResultEnum.SUCCESS) {
            const toPath = decodeURIComponent((route.query?.redirect || '/') as string);
            message.success('登录成功，即将进入系统');
            if (route.name === LOGIN_NAME) {
              router.replace('/');
            } else router.replace(toPath);
          } else {
            message.info(msg || '登录失败');
          }
        } finally {
          loading.value = false;
        }

      } else {
        message.error('请填写完整信息，并且进行验证码校验');
      }
    });
  };

  const sendcode = () => {
    if (timeLimit.value >= 0) return;
    if (!formInline.username) {
      message.warning("请先输入手机号")
      return
    }
    sendCode({
      telephone: formInline.username
    }).then(res => {
      if (res.code === 200) {
        message.success('发送成功');
        timeLimit.value = 60;
        sendCodeMsg.value = `${timeLimit.value}秒`;
        timer.value = setInterval(() => {
          timeLimit.value -= 1;
          if (timeLimit.value >= 0) {
            sendCodeMsg.value = `${timeLimit.value}秒`;
          } else {
            sendCodeMsg.value = '发送';
            clearInterval(timer.value);
            timer.value = null;
          }
        }, 1000);
      }
    })
  }

  const saveInfoFlag = localStorage.getItem('saveInfo');
  if (saveInfoFlag === '0') {
    saveInfo.value = false;
  }
  const loginInfo = localStorage.getItem('loginInfo');
  if (loginInfo) {
    const info = JSON.parse(loginInfo);
    if (info.username) {
      formInline.username = info.username;
    }
    if (info.password) {
      formInline.password = info.password;
    }
  }
</script>

<style lang="less" scoped>
  .view-account {
    display: flex;
    flex-direction: column;
    height: 100vh;
    overflow: auto;

    &-container {
      flex: 1;
      padding: 32px 12px;
      max-width: 384px;
      min-width: 320px;
      margin: 0 auto;
    }

    &-top {
      padding: 32px 0;
      text-align: center;

      &-logo {
        text-align: center;

        img {
          display: block;
          margin: auto;
          width: 160px;
        }
      }

      &-desc {
        font-size: 14px;
        color: #808695;
      }
    }

    &-other {
      width: 100%;
    }

    .default-color {
      color: #515a6e;

      .ant-checkbox-wrapper {
        color: #515a6e;
      }
    }
  }

  @media (min-width: 768px) {
    .view-account {
      background-image: url('../../assets/images/login.svg');
      background-repeat: no-repeat;
      background-position: 50%;
      background-size: 100%;
    }

    .page-account-container {
      padding: 32px 0 24px 0;
    }
  }
</style>
